import {app, BrowserWindow, dialog, globalShortcut, ipcMain, Menu, nativeImage, Tray, Notification} from "electron";
import path from "node:path";
import {fileURLToPath} from "node:url";
import fs from "node:fs";
import mimeType from "mime-types";

const windowObj = {}

const __dirname = path.dirname(fileURLToPath(import.meta.url))

ipcMain.handle('readFileSync', (_, url, encoding = 'utf8') => {
    return fs.readFileSync(path.join(__dirname, url), {encoding})
})
ipcMain.handle('readSystemFile', (_, url, encoding = 'utf8') => {
    return new Promise((resolve) => {
        return fs.readFile(path.join(url), {encoding}, (err, data) => {
            resolve({err, data})
        })
    })
})
ipcMain.handle('deleteSystemFile', (_, url) => {
    return new Promise((resolve, reject) => {
        return fs.unlink(path.join(url), (err) => {
            if (err !== null) {
                reject(err)
            } else {
                resolve()
            }
        })
    })
})
ipcMain.handle('writeFileSync', (_, url, data, encoding = 'utf8') => {
    return fs.writeFileSync(path.join(__dirname, url), data, {encoding})
})
ipcMain.handle('writeSystemFile', (_, url, data, encoding = 'utf8') => {
    return new Promise((resolve) => {
        fs.writeFile(path.join(url), data, {encoding}, (err) => {
            resolve(err)
        })
    })
})
ipcMain.handle('appendSystemFile', (_, url, data, encoding = 'utf8') => {
    return new Promise((resolve) => {
        fs.appendFile(path.join(url), data, {encoding}, (err) => {
            resolve(err)
        })
    })
})
ipcMain.handle('existsSync', (_, url) => {
    return fs.existsSync(path.join(__dirname, url))
})
ipcMain.handle('message', (_, title, message, type = "info") => {
    return dialog.showMessageBox(windowObj.MainWindow, {
        type: type,
        title: title,
        message: message,
        buttons: ['确定'],
    })
})

const devTools = (win) => {
    if (process.env.NODE_ENV === 'development') {
        const current = windowObj[win]
        if (current.webContents.isDevToolsOpened()) {
            current.webContents.closeDevTools()
        } else {
            current.webContents.openDevTools()
        }

    }
}

ipcMain.on('win', (_, win, type) => {
    switch (type) {
        case 'devTools':
            devTools(win)
            break
        case 'hide':
            windowObj[win].hide()
            break
    }
})

ipcMain.handle('getFile', (_, opt = {}) => {
    return dialog.showOpenDialog({
        title: opt.title ?? '',
        defaultPath: opt.defaultPath ?? '',
        filters: opt.filters ?? [],
        properties: opt.properties ?? [],
        buttonLabel: opt.buttonLabel ?? ''
    })
})
ipcMain.handle('getFileType', (_, name) => {
    return mimeType.lookup(name)
})
ipcMain.handle('getFileBasename', (_, name) => {
    return path.basename(name)
})

ipcMain.handle('saveFile', (_, opt = {}) => {
    return dialog.showSaveDialog({
        title: opt.title ?? '',
        defaultPath: opt.defaultPath ?? '',
        filters: opt.filters ?? [],
        properties: opt.properties ?? [],
        buttonLabel: opt.buttonLabel ?? ''
    })
})

ipcMain.on('notify', (_, opt = {}) => {
    if (opt.icon) {
        opt.icon = nativeImage.createFromPath(path.join(__dirname, opt.icon))
    }
    const notify = new Notification(opt)
    notify.show()
})

ipcMain.on('runApp', (_, appData) => {
    if (!windowObj.app) {
        windowObj.app = {}
    }
    const appPath = path.join(__dirname, 'micro-app', appData.packageName)
    if (windowObj.app[appData.packageName]) {
        windowObj.app[appData.packageName].show()
        return
    }
    let webPreferencesOther = {}
    if (appData.preload) {
        webPreferencesOther.preload = path.join(__dirname, 'microApp.preload.js')
    }

    windowObj.app[appData.packageName] = new BrowserWindow({
        title: appData.name,
        width: appData.width,
        height: appData.height,
        resizable: appData.resize ?? false,
        show: false,
        webPreferences: {
            ...webPreferencesOther,
            webSecurity: false
        }
    })
    if (appData.ua) {
        windowObj.app[appData.packageName].webContents.setUserAgent(appData.ua)
    }

    if (appData.type === 'remote') {
        windowObj.app[appData.packageName].loadURL(appData.path)
    } else {
        windowObj.app[appData.packageName].loadFile(path.join(appPath, appData.path))
    }
    windowObj.app[appData.packageName].webContents.setWindowOpenHandler((detail) => {
        if (detail.type === 'remote') {
            windowObj.app[appData.packageName].loadURL(detail.url)
        } else {
            windowObj.app[appData.packageName].loadFile(detail.url)
        }
    })


    const template = [
        {
            label: '菜单',
            submenu: [
                {
                    label: '采集完成',
                    click: async () => {
                        console.log('Open clicked');
                        // 在这里添加打开文件的逻辑
                        // 获取 windowObj.app[appData.packageName] 的cookie
                        const cookies = await windowObj.app[appData.packageName].webContents.session.cookies.get({})
                        console.log(cookies)
                        //     获取localStorage
                        // const localStorage = await windowObj.app[appData.packageName].webContents.executeJavaScript('localStorage')
                        // console.log(localStorage)
                    },
                }
            ]
        }
    ]
    // 创建菜单
    const menu = Menu.buildFromTemplate(template);
    windowObj.app[appData.packageName].setMenu(menu)
    windowObj.app[appData.packageName].on('ready-to-show', () => {
        windowObj.app[appData.packageName].show()
        //     打开控制台
        windowObj.app[appData.packageName].webContents.openDevTools()
    })
    windowObj.app[appData.packageName].on('close', () => {
        windowObj.app[appData.packageName] = null
    })
})

const createMainWindow = function () {
    windowObj.MainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            webSecurity: false,
            preload: path.join(__dirname, 'preload.mjs')
        }
    })

    windowObj.MainWindow.setMenu(null)
    // windowObj.MainWindow.maximize()
    windowObj.MainWindow.send('currentWindow', 'MainWindow')

    windowObj.MainWindow.once('ready-to-show', () => {
        windowObj.MainWindow.show()
    })

    windowObj.MainWindow.on('close', (event) => {
        event.preventDefault()
        windowObj.MainWindow.hide()
    })
    windowObj.MainWindow.webContents.openDevTools()
    if (process.env.NODE_ENV === 'development') {
        windowObj.MainWindow.loadURL(process.env['VITE_DEV_SERVER_URL'])
    } else {
        windowObj.MainWindow.loadFile(path.join(__dirname, './index.html'))
    }
}

app.whenReady().then(res => {
    const icon = nativeImage.createFromPath(path.join(__dirname, 'logo.png'))
    const tray = new Tray(icon)
    tray.on('click', () => {
        windowObj.MainWindow.show()
    })
    const contextMenu = Menu.buildFromTemplate([{
        label: '打开主界面',
        click: () => {
            windowObj.MainWindow.show()
        }
    }, {
        label: '退出',
        click: () => {
            app.quit()
        }
    }])
    tray.setContextMenu(contextMenu)
    tray.setToolTip('宇成客')

    let keyString = process.platform === 'darwin' ? 'CommandOrControl+Shift+O' : 'CommandOrControl+Shift+O'
    globalShortcut.register(keyString, () => {
        windowObj.MainWindow.show();
        windowObj.MainWindow.maximize();
    })
    createMainWindow()
})
